<template>
  <div class="sxImage">
    <div v-if="isLoading">
      <i class="el-icon-loading"></i>
    </div>
    <span v-else-if="isError">
      <i class="el-icon-picture-outline"></i>
    </span>
    <img
      v-else
      slot="reference"
      ref="img"
      loading="lazy"
      class="sxImage__image"
      v-bind="$attrs"
      :src="src"
      :alt="alt"
      v-on="$listeners"
    />
  </div>
</template>

<script>
export default {
  props: {
    src: String,
    alt: String,
    thumbVisible: Boolean,
    thumbDirection: {
      type: String,
      default: 'left',
      validator: val => {
        return [
          'top',
          'top-start',
          'top-end',
          'bottom',
          'bottom-start',
          'bottom-end',
          'left',
          'left-start',
          'left-end',
          'right',
          'right-start',
          'right-end'
        ].includes(val)
      }
    }
  },
  data() {
    return {
      isLoading: true,
      isError: false
    }
  },
  watch: {
    src: {
      handler(val) {
        const ignoreUrl = []
        if (ignoreUrl.includes(val)) {
          this.handleError()
        } else {
          this.loadImage()
        }
      },
      immediate: true
    }
  },
  methods: {
    loadImage() {
      this.isLoading = true
      this.isError = false
      const img = new Image()
      img.onload = e => this.handleLoad(e, img)
      img.onerror = this.handleError.bind(this)

      Object.keys(this.$attrs).forEach(key => {
        const value = this.$attrs[key]
        img.setAttribute(key, value)
      })
      img.src = this.src
    },
    handleLoad(e, img) {
      this.isLoading = false
    },
    handleError() {
      this.isError = true
      this.isLoading = false
      this.$emit('error')
    }
  }
}
</script>

<style scoped lang="scss">
.sxImage {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  &__image {
    width: 100%;
    height: 100%;
    display: inline-block;
    object-fit: contain;
  }
  &__thumb {
    width: 200px;
    height: 200px;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center center;
  }
}
</style>
